# application/mapper/detection/product_coil.py
from application.extensions.databases import db
from application.extensions.logging import system_logger
from application.models.detection.product_coil import ProductCoil
from typing import List, Dict, Any
from datetime import datetime


class ProductCoilMapper:
    """绕组数据访问层"""

    @staticmethod
    def get_product_coil_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> tuple:
        """
        分页获取绕组数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (绕组数据列表, 总数)
        """
        query = db.session.query(ProductCoil).filter(ProductCoil.del_flag == 0)

        # 添加查询条件
        if conditions:
            if conditions.get("coil"):
                query = query.filter(
                    ProductCoil.coil.like(f"%{conditions['coil']}%")
                )
            if conditions.get("productModelId"):
                query = query.filter(
                    ProductCoil.product_model_id == conditions['productModelId']
                )
            if conditions.get("coilAccuracyLevel"):
                query = query.filter(
                    ProductCoil.coil_accuracy_level.like(f"%{conditions['coilAccuracyLevel']}%")
                )
            if conditions.get("coilType"):
                query = query.filter(
                    ProductCoil.coil_type.like(f"%{conditions['coilType']}%")
                )

        # 获取总数
        total = query.count()

        # 分页查询，按创建时间倒序排列
        offset = (page_num - 1) * page_size
        coil_list = (
            query.order_by(ProductCoil.create_time.desc())
            .offset(offset)
            .limit(page_size)
            .all()
        )

        return coil_list, total

    @staticmethod
    def get_product_coil_by_id(coil_id: int) -> ProductCoil:
        """
        根据ID获取绕组
        :param coil_id: 绕组ID
        :return: 绕组对象
        """
        return (
            db.session.query(ProductCoil)
            .filter(
                ProductCoil.coil_id == coil_id,
                ProductCoil.del_flag == 0
            )
            .first()
        )

    @staticmethod
    def get_coils_by_product_model(product_model_id: int) -> List[ProductCoil]:
        """
        根据产品型号ID获取绕组列表
        :param product_model_id: 产品型号ID
        :return: 绕组列表
        """
        return (
            db.session.query(ProductCoil)
            .filter(
                ProductCoil.product_model_id == product_model_id,
                ProductCoil.del_flag == 0
            )
            .order_by(ProductCoil.create_time.desc())
            .all()
        )

    @staticmethod
    def create_product_coil(coil: ProductCoil) -> ProductCoil:
        """
        创建绕组
        :param coil: 绕组对象
        :return: 创建后的绕组对象
        """
        # 确保新创建的记录 del_flag 为 0
        if not hasattr(coil, 'del_flag') or coil.del_flag is None:
            coil.del_flag = 0
            
        db.session.add(coil)
        db.session.commit()
        return coil

    @staticmethod
    def update_product_coil(coil: ProductCoil) -> ProductCoil:
        """
        更新绕组
        :param coil: 绕组对象
        :return: 更新后的绕组对象
        """
        db.session.commit()
        return coil

    @staticmethod
    def batch_delete_product_coil(coil_ids: list) -> int:
        """
        批量逻辑删除绕组
        :param coil_ids: 绕组ID列表
        :return: 删除的记录数
        """
        try:
            # 执行批量逻辑删除，将 del_flag 设置为 1
            updated_count = db.session.query(ProductCoil).filter(
                ProductCoil.coil_id.in_(coil_ids),
                ProductCoil.del_flag == 0  # 只更新未删除的记录
            ).update(
                {ProductCoil.del_flag: 1},
                synchronize_session=False
            )
            
            db.session.commit()
            return updated_count
        except Exception as e:
            db.session.rollback()
            system_logger.error(f"批量逻辑删除绕组失败: {e}")
            raise e